<template>
  <el-drawer
    v-model="drawerVisible"
    :z-index="1000"
    :destroy-on-close="true"
    size="500px"
    :title="`${drawerProps.title}`"
    :before-close="_colse"
  >
    <el-form ref="examFormRef" label-width="100px" label-suffix=" :" :model="drawerProps.row" v-if="drawerProps.row">
      <!-- <div class="handlerBar">
        <div class="handlerBar__header">
          <el-button type="primary" plain :icon="CirclePlus" @click="_addControlItem">新增控制信息</el-button>
        </div>
      </div> -->
      <div class="controlList">
        <div class="controlItem" v-for="item in controlList" :key="item.id">
          <!-- <el-icon class="delBtn" :size="20"><CircleClose @click="_delControlItem(index)" /></el-icon> -->
          <el-select class="controlId" v-model="item.deviceId" clearable placeholder="请选择装置名称" disabled>
            <el-option v-for="val in deviceSelList" :key="val.deviceId" :label="val.deviceName" :value="val.deviceId" />
          </el-select>
          <el-select v-model="item.studentId" clearable placeholder="请选择学生">
            <el-option v-for="val in studentSelList" :key="val.userId" :label="val.userName" :value="val.userId" />
          </el-select>
        </div>
      </div>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="_colse">取消</el-button>
        <el-button type="primary" @click="_submit">确认</el-button>
      </span>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="ResetPsdDrawer">
import { ref } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { ResultData, Exam } from "@/api/interface";
// import { CirclePlus } from "@element-plus/icons-vue";
import { getCabinetSelList } from "@/api/modules/files1Manage/cabinet";
import { getUserSelList } from "@/api/modules/user";
import { useRouter } from "vue-router";
import { getExamDtl } from "@/api/modules/exam1Manage/examInfo";
interface drawerProps {
  title: string;
  row: Partial<Exam.ResExamInfoList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  resetTableList?: () => void;
}
const router = useRouter();

const drawerVisible = ref(false);
const drawerProps = ref<drawerProps>({
  title: "",
  row: {}
});

const examFormRef = ref<FormInstance>();
const deviceSelList: any = ref([]);
const controlList: any = ref([]);
const studentSelList: any = ref([]);
// 接收父组件传过来的参数
const acceptParams = async (params: drawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  const { result } = (await getExamDtl({ testId: drawerProps.value.row.testId as number })) as ResultData;
  result.controlList.forEach((item: any, index: number) => {
    controlList.value.push({ id: index + 1, controlId: item.controlId, deviceId: item.deviceId, studentId: item.studentId });
  });

  getCabinetSelData();
  getUserSelData();
};

/**
 * 新增控制信息
 */
// const _addControlItem = () => {
//   controlList.value.push({ id: controlList.value.length + 1, controlId: "", studentId: "" });
// };
/**
 * 删除控制信息
 */
// const _delControlItem = (curIdx: number) => {
//   controlList.value.splice(curIdx, 1);
// };
/**
 * 关闭弹窗
 */
const _colse = () => {
  drawerVisible.value = false;
  controlList.value = [];
  examFormRef.value && examFormRef.value.resetFields();
};

/**
 * 获取设备选择列表
 */
const getCabinetSelData = async () => {
  const { result } = (await getCabinetSelList({ pageNum: 1, pageSize: 100000000 })) as ResultData;
  deviceSelList.value = result.dataList;
};

/**
 * 获取用户选择列表
 */
const getUserSelData = async () => {
  const res = await getUserSelList({ userType: "student" });
  studentSelList.value = res.dataList;
};

const getSendRecord = async (testId: number) => {
  controlList.value = [];
  router.push(`/exam1Manage/examControl/sendRecordDtl/${testId}`);
  drawerVisible.value = false;
};
/**
 * 提交修改信息
 */
const _submit = async (): Promise<void> => {
  examFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      interface params {
        testId: number;
        controlList?: { controlId: string; studentId: string }[];
      }
      let { testId } = drawerProps.value.row;
      let params: params = { testId: testId as number, controlList: [] };
      let isReturn = false;

      params.controlList = controlList.value.map((item: any) => {
        if (isReturn) return false;

        if (!item.controlId) {
          isReturn = true;
        } else if (!item.studentId) {
          isReturn = true;
        }

        try {
          if (isReturn) {
            ElMessage.error("请检查控制信息,控制信息子项不能为空");
            throw Error();
          }
        } catch (err: any) {
          console.log(err.message);
        }
        return {
          controlId: item.controlId,
          studentId: item.studentId
        };
      });

      if (params.controlList && !params.controlList.length) {
        ElMessage.error("请新增控制信息，控制信息不能为空");
        return false;
      }
      if (isReturn) return false;

      await drawerProps.value.api!(params);
      getSendRecord(drawerProps.value.row.testId as number);
    } catch (error) {
      console.log(error);
    }
  });
};
defineExpose({
  acceptParams
});
</script>
<style lang="scss" scope>
.handlerBar {
  width: 100%;
  .handlerBar__header {
    padding: 0 10px;
  }
}
.controlItem {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  margin: 20px 0 0;
  border: 1px solid #eeeeee;
  .controlId {
    margin-right: 20px;
  }
  .delBtn {
    position: absolute;
    top: -8px;
    right: -8px;
    color: var(--el-color-danger);
    cursor: pointer;
  }
}
</style>
